package com.wesleyone.sc.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.wesleyone.sc.entities.CommonResult;
import com.wesleyone.sc.entities.Payment;
import com.wesleyone.sc.handler.CustomerBlockHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author: wesleyOne
 * @Email: wesleyone666@163.com
 * @Gitee: https://gitee.com/wesleyOne
 * @Date: 2020/8/30
 */
@RestController
public class TestController {

    @Value("${server.port}")
    private String port;

    @GetMapping(value = "/helloA")
    public String helloA() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "HelloA Sentinel===AAAAAA";
    }

    @GetMapping(value = "/helloB")
    public String helloB() {
        return "helloB Sentinel===BBBBBB";
    }

    @GetMapping(value = "/helloC")
    public String helloC() {
        int i = 10/0;
        return "helloC Sentinel===CCCCCC";
    }

    @SentinelResource(value="testHotKey", blockHandler = "deal_testHotKey")
    @GetMapping(value = "/testHotKey")
    public String testHotKey(
            @RequestParam(value = "p1", required = false) String p1,
            @RequestParam(value = "p2", required = false) String p2
            ) {
        return "-------testHotKey";
    }

    public String deal_testHotKey(String p1, String p2, BlockException blockException) {
        return "deal_testHotKey：\n"+blockException;
    }

    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "handleException")
    public CommonResult byResource() {
        return new CommonResult(200, "按资源名称限流测试OK", new Payment());
    }

    public CommonResult handleException(BlockException exception) {
        return new CommonResult(444, exception.toString());
    }

    @GetMapping("/rateLimit/byUrl")
    @SentinelResource(value = "byUrl", blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handlerException")
    public CommonResult byUrl() {
        return new CommonResult(200, "按URL限流测试OK", new Payment(2020L, "serial002", port));
    }

}
